package org.wzq.android_api;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * AsynTask 实现 文件下载
 * AsynTask.exec(<T> param) 也可以 传递T的数组，所以doInBackground(T...params)
 */
public class Act_AsynTask extends Activity {
    final String TAG = Act_AsynTask.class.getSimpleName();
    //
    Button btnStartAsyn;
    ProgressBar pbDownloader;
    TextView tvShowPercent;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_asyn_task);

        initVar();

        btnStartAsyn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                FileDownloader task = new FileDownloader();
                // 测试,文件 ~ 4.5M
                task.execute("https://codeload.github.com/apache/poi/zip/BUILD_BRANCH");
            }
        });
    }

    private void initVar() {
        btnStartAsyn = (Button) findViewById(R.id.btn_start_asyn);
        pbDownloader = (ProgressBar) findViewById(R.id.pb);
        tvShowPercent = (TextView) findViewById(R.id.tv_show_percent);
    }

    /**
     * AsyncTask<Params, Progress, Result>
     */
    private class FileDownloader extends AsyncTask<String, Float, String> {

        @Override
        protected void onPreExecute() {
            Log.v(TAG, "onPreExecute");
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            Log.v(TAG, "doInBackground");
            try {
                URL url = new URL(params[0]);
                URLConnection conn = url.openConnection();
                //
                InputStream is = conn.getInputStream();

                int totalSize = conn.getContentLength();//根据响应获取文件大小
                if(totalSize <= 0) {
                    Log.e(TAG, "无法获知文件大小 ");
                    return null;
                }
                if(is == null) {
                    Log.e(TAG, "stream is null");
                    return null;
                }

                String savePath = Environment.getExternalStorageDirectory() + "/dev/poi-BUILD_BRANCH.zip";
                File f = new File(savePath);
                if(!f.getParentFile().exists()) {
                    f.getParentFile().mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(savePath);

                byte buf[] = new byte[1024];
                int downLoadFileSize = 0;
                publishProgress((float) downLoadFileSize / totalSize);

                do {
                    //循环读取
                    int numread = is.read(buf);
                    if(numread == -1) {
                        break;
                    }
                    fos.write(buf, 0, numread);
                    downLoadFileSize += numread;

                    publishProgress((float) downLoadFileSize / totalSize);
                } while(true);

                is.close();

                return savePath;
            } catch(IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        //这个函数在doInBackground调用publishProgress时触发,1个参数用progesss[0]来取值
        @Override
        protected void onProgressUpdate(Float... values) {
            Log.v(TAG, "onProgressUpdate");

            float f = values[0];
            tvShowPercent.setText(values[0] + "");
            pbDownloader.setProgress((int) (100 * values[0]));
        }

        @Override
        protected void onPostExecute(String fileSavePath) {
            Log.v(TAG, "onPostExecute");
            Log.v(TAG, "file saved in= " + fileSavePath);
            super.onPostExecute(fileSavePath);
        }


        @Override
        protected void onCancelled() {
            Log.v(TAG, "onCancelled");
            super.onCancelled();
        }
    }
}
